package cn.kgc.ssm.controller;

import cn.hutool.captcha.LineCaptcha;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author 课工场
 * @date 2024/11/15
 * @description   验证码请求控制层
 */
@Controller
@RequestMapping("captcha")
public class CaptchaController {

    //  生成一张验证码图片
    @GetMapping
    public void  createCaptcha(HttpServletRequest request, HttpServletResponse response){

        LineCaptcha lineCaptcha = new LineCaptcha(100, 38, 4, 3);

        // 获取图片验证码 并保存
        String code = lineCaptcha.getCode();
        HttpSession session = request.getSession();
        session.setAttribute("code",code);

        // 将验证码图片写出到浏览器
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            lineCaptcha.write(outputStream);
            outputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

}
